"""用户相关路由"""
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import Optional
from app.config.database import get_db
from app.controllers.user_controller import user_controller
from app.middlewares.auth import get_current_user, get_optional_current_user
from app.schemas.user import UserCreate, UserUpdate, TokenResponse, UserResponse
from app.schemas.common import ResponseModel, PageResponse

router = APIRouter(prefix="/api/users", tags=["users"])


@router.post("/register", response_model=ResponseModel[dict])
def register_user(
    user_data: UserCreate,
    db: Session = Depends(get_db)
):
    """用户注册"""
    try:
        user = user_controller.create_user(db, user_data)
        return ResponseModel(
            code=200,
            message="注册成功",
            data={
                "id": user.id,
                "username": user.username,
                "nickname": user.nickname,
                "avatar": user.avatar
            }
        )
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/login", response_model=ResponseModel[TokenResponse])
def login(
    username: str = Query(..., description="用户名"),
    password: str = Query(..., description="密码"),
    db: Session = Depends(get_db)
):
    """用户登录"""
    try:
        token_data = user_controller.login(db, username, password)
        return ResponseModel(
            code=200,
            message="登录成功",
            data=token_data.dict()
        )
    except ValueError as e:
        raise HTTPException(status_code=401, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/profile/{user_id}", response_model=ResponseModel[dict])
def get_user_profile(
    user_id: int,
    db: Session = Depends(get_db),
    current_user_id: Optional[int] = Depends(get_optional_current_user)
):
    """获取用户资料"""
    try:
        profile = user_controller.get_user_profile(db, user_id, current_user_id)
        if not profile:
            raise HTTPException(status_code=404, detail="用户不存在")
        return ResponseModel(
            code=200,
            message="success",
            data=profile
        )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.put("/profile", response_model=ResponseModel[dict])
def update_profile(
    user_update: UserUpdate,
    db: Session = Depends(get_db),
    current_user_id: int = Depends(get_current_user)
):
    """更新用户资料"""
    try:
        user = user_controller.update_user(db, current_user_id, user_update)
        if not user:
            raise HTTPException(status_code=404, detail="用户不存在")
        return ResponseModel(
            code=200,
            message="更新成功",
            data={
                "id": user.id,
                "username": user.username,
                "nickname": user.nickname,
                "avatar": user.avatar,
                "email": user.email,
                "gender": user.gender,
                "bio": user.bio
            }
        )
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/videos/{user_id}", response_model=ResponseModel[PageResponse])
def get_user_videos(
    user_id: int,
    page: int = Query(1, ge=1, description="页码"),
    pageSize: int = Query(10, ge=1, le=50, description="每页数量"),
    db: Session = Depends(get_db)
):
    """获取用户发布的视频列表"""
    try:
        result = user_controller.get_user_videos(db, user_id, page, pageSize)
        return ResponseModel(
            code=200,
            message="success",
            data=result
        )
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/liked/{user_id}", response_model=ResponseModel[PageResponse])
def get_user_liked_videos(
    user_id: int,
    page: int = Query(1, ge=1, description="页码"),
    pageSize: int = Query(10, ge=1, le=50, description="每页数量"),
    db: Session = Depends(get_db)
):
    """获取用户点赞的视频列表"""
    try:
        result = user_controller.get_user_liked_videos(db, user_id, page, pageSize)
        return ResponseModel(
            code=200,
            message="success",
            data=result
        )
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/favorites/{user_id}", response_model=ResponseModel[PageResponse])
def get_user_favorite_videos(
    user_id: int,
    page: int = Query(1, ge=1, description="页码"),
    pageSize: int = Query(10, ge=1, le=50, description="每页数量"),
    db: Session = Depends(get_db)
):
    """获取用户收藏的视频列表"""
    try:
        result = user_controller.get_user_favorite_videos(db, user_id, page, pageSize)
        return ResponseModel(
            code=200,
            message="success",
            data=result
        )
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/follow/{user_id}", response_model=ResponseModel[dict])
def follow_user(
    user_id: int,
    db: Session = Depends(get_db),
    current_user_id: int = Depends(get_current_user)
):
    """关注用户"""
    try:
        success = user_controller.follow_user(db, current_user_id, user_id)
        return ResponseModel(
            code=200,
            message="关注成功",
            data={"success": success}
        )
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.delete("/follow/{user_id}", response_model=ResponseModel[dict])
def unfollow_user(
    user_id: int,
    db: Session = Depends(get_db),
    current_user_id: int = Depends(get_current_user)
):
    """取消关注用户"""
    try:
        success = user_controller.unfollow_user(db, current_user_id, user_id)
        return ResponseModel(
            code=200,
            message="取消关注成功",
            data={"success": success}
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
